<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ activityId ? $t('message.bjhd') : $t('message.xzhd') }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> {{ $t('message.fhsyy') }}
      </div>
    </div>

    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <div class="property-title">{{ $t('message.hdxx') }}</div>
      <el-form-item :label="$t('message.hdhb')" prop="showPoster">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="ACTIVITY_IMG"
            :fixed-number="[690, 388]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <div class="df_ac">
          <el-upload
            class="device-uploader"
            accept=".jpg,.png"
            :auto-upload="false"
            :action="uploadFileUrl"
            :data="uploadData"
            :show-file-list="false"
            :on-change="addFileChange"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="param.showPoster"
              class="file"
              :style="'background-image: url(' + param.showPoster + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
          <div class="placeholder9">
            <div>{{ $t('message.jycc') }}：{{ "690px X 388px" }}</div>
            <div>
              {{ $t('message.zctpsm') }}
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.hdname')" prop="name">
        <el-input
          v-model="param.name"
          class="w400"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.hdname')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="$t('message.hdjg')" prop="price">
        <el-input
          v-model="param.price"
          class="w400"
          type="number"
          :disabled="
            (Boolean(activityId) && activityStatus === '1') ||
              (Boolean(activityId) && activityStatus === '2')
          "
          oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1');"
          :placeholder="$t('message.qsr') + $t('message.hdjg')"
        />
      </el-form-item>
      <div style="display: flex; align-items: center">
        <el-form-item :label="$t('message.hdsj')" prop="startTime">
          <el-date-picker
            v-model="param.startTime"
            type="datetime"
            :placeholder="$t('message.qxz') + $t('message.ksrqsj')"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <div class="division-line" style="margin-bottom: 22px">~</div>
        <el-form-item label-width="0" prop="endTime">
          <el-date-picker
            v-model="param.endTime"
            type="datetime"
            :placeholder="$t('message.qxz') + $t('message.jsrqsj')"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>
      </div>
      <el-form-item :label="$t('message.hddd')" prop="siteName">
        <el-input
          v-model="param.siteName"
          class="w400"
          type="text"
          :placeholder="$t('message.qxz') + $t('message.hddd')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="$t('message.bmrs')" prop="isXz">
        <el-radio-group v-model="param.isXz">
          <el-radio label="0">{{ $t('message.bxg') }}</el-radio>
          <el-radio label="1">{{ $t('message.xgrs') }}</el-radio>
        </el-radio-group>
        <el-input
          v-if="param.isXz== 1"
          v-model="param.signLimit"
          oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
          maxlength="10"
          class="w200 ml10"
        >
          <template #append>{{ $t('message.ren') }}</template>
        </el-input>
        <span class="placeholder6 ml20">{{ $t('message.hdzdbmrs') }}</span>
      </el-form-item>
      <el-form-item :label="$t('message.bmjzsj')" prop="applyEndTime">
        <el-date-picker
          v-model="param.applyEndTime"
          :picker-options="pickerOptions"
          type="datetime"
          class="w400"
          :disabled="Boolean(activityId) && activityStatus === '2'"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          :placeholder="$t('message.xzrq')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.hdjljf')" prop="shareIntegral">
        <el-input
          v-model="param.shareIntegral"
          class="w400"
          onkeyup="value=value.replace(/[^\d^\.]/g,'')"
          oninput="if(value<0) { value = ''}"
          type="number"
          :disabled="Boolean(activityId) && activityStatus !== '0'"
          :placeholder="$t('message.qxz') + $t('message.hdjljf')"
        />
        <div class="placeholder9">{{ $t('message.hdbmhdjf') }}</div>
      </el-form-item>
      <el-form-item :label="$t('message.hylx')" prop="cardTypeList">
        <el-select
          v-model="param.cardTypeList"
          multiple
          collapse-tags
          filterable
          class="w400"
          :placeholder="$t('message.qxz') + $t('message.hylx')"
        >
          <el-option
            v-for="item in vipTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('message.zklx')" prop="discountType">
        <el-select
          v-model="param.discountType"
          class="w400"
          :disabled="Boolean(activityId) && activityStatus !== '0'"
          :placeholder="$t('message.qxz') + $t('message.zklx')"
        >
          <el-option
            v-for="item in zkList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div
        v-if="param.discountType == '1'"
        style="display: flex; flex-wrap: wrap"
      >
        <el-form-item
          v-for="vip in vipTypes"
          :key="vip.id"
          align="center"
          :label="vip.name || vip.cardName"
          style="width: 50%"
          :prop="`discountMap.${vip.id}`"
          :rules="{
            required: true,
            message: $t('message.qsr') + $t('message.hyzk'),
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="param.discountMap[vip.id]"
            :disabled="
              Boolean(activityId) && activityStatus !== '0' && vip.disabled
            "
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            type="text"
            :placeholder="$t('message.qsr') + $t('message.hyzk') + '(' + $t('message.bllwxs') + ')'"
            maxlength="50"
          />
        </el-form-item>
      </div>
      <el-form-item :label="$t('message.sort')" prop="sortNum">
        <el-input
          v-model="param.sortNum"
          class="w400"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.sort')"
          maxlength="10"
          oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
        />
      </el-form-item>
      <div class="line-style" />

      <div class="property-title">{{ $t('message.xqxx') }}</div>
      <el-form-item :label="$t('message.hdzt')" prop="theme">
        <el-input
          v-model="param.theme"
          class="w400"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.hdzt')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="$t('message.zbf')" prop="sponsor">
        <el-input
          v-model="param.sponsor"
          class="w400"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.zbf')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="$t('message.cbf')" prop="organizer">
        <el-input
          v-model="param.organizer"
          class="w400"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.cbf')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="$t('message.hdxq')" prop="info">
        <div class="secondColor">{{ $t('message.tpbnfz') }}</div>
        <quill-editor
          ref="myTextEditor"
          v-model="param.info"
          :placeholder="$t('message.qsr') + $t('message.hdxq')"
          class="myQuillEditor"
          :options="quillOption"
        />
        <!-- <WangEditor
          ref="myTextEditor"
          :value="param.info"
          @input="(e) => $set(param, 'info', e)"
        /> -->
      </el-form-item>

      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >{{ $t('message.tj') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import WangEditor from '@/components/quillOption'
import { quillEditor } from 'vue-quill-editor'
import quillConfig from '@/api/sc.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Cropper from '@/components/cropper'
import {
  uploadFile,
  cardList,
  // getProjectList,
  // getAreaList,
  spaceList,
  startActivity,
  activityQueryForEdit,
  activitySaveForEdit
} from '@/api'
export default {
  name: 'ActivityManagementAdd',
  components: {
    quillEditor,
    Cropper
  },
  data() {
    return {
      quillOption: quillConfig,
      activityId: '',
      activityStatus: '',
      uploadFileUrl: uploadFile,
      dialogCropperVisible: false,
      subLoading: false,
      vipTypes: [],
      param: {
        discountMap: {},
        isXz: '0',
        cardTypeList: [],
        discountType: '0'
      },
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      },
      uploadData: {
        folder: 'ACTIVITY_IMG',
        type: ''
      },
      zkList: [
        { value: '0', label: this.$t('message.mrzk') },
        { value: '1', label: this.$t('message.zdyzk') }
      ],
      jlList: [],
      venueId: sessionStorage.getItem('venueId'),
      rules: {
        showPoster: [
          { required: true, message: this.$t('message.qsc') + this.$t('message.hdhb'), trigger: 'blur' }
        ],
        name: [{ required: true, message: this.$t('message.qsr') + this.$t('message.hdmc'), trigger: 'blur' }],
        price: [{ required: true, message: this.$t('message.qsr') + this.$t('message.hdjg'), trigger: 'blur' }],
        startTime: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.hdkssj'), trigger: 'change' }
        ],
        endTime: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.hdjssj'), trigger: 'change' }
        ],
        siteName: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.hddd'), trigger: 'blur' }
        ],
        applyEndTime: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.bmjzsj'), trigger: 'blur' }
        ],
        shareIntegral: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.hdjljf'), trigger: 'blur' }
        ],
        theme: [{ required: true, message: this.$t('message.qsr') + this.$t('message.hdzt'), trigger: 'blur' }],
        sponsor: [{ required: true, message: this.$t('message.qsr') + this.$t('message.zbf'), trigger: 'blur' }],
        organizer: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.cbf'), trigger: 'blur' }
        ],
        info: [{ required: true, message: this.$t('message.qsr') + this.$t('message.hdxq'), trigger: 'blur' }],
        discountType: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.zklx'), trigger: 'change' }
        ],
        optionImg: '',
        files: {},
        fileinfo: {}
      }
    }
  },
  created() {
    this.getCardList()
    if (this.$route.query.id) {
      this.getActivityDetailInfo(this.$route.query.id)
      this.activityId = this.$route.query.id
      if (this.$route.query.type && this.$route.query.type === 'copy') {
        this.activityId = ''
      } else {
        this.activityStatus = this.$route.query.status
      }
    } else {
      this.activityId = ''
    }
  },
  activated() {
    // if (this.$route.query.id) {
    //   this.getActivityDetailInfo(this.$route.query.id)
    // } else {
    //   this.param = {
    //     discountMap: {}
    //   }
    //   this.fileinfo = {}
    //   setTimeout(() => {
    //     this.$refs.ruleForm.clearValidate()
    //   }, 2000)
    // }
  },
  methods: {
    check_num(e) {
      this.param.rs[e] = this.param.rs[e].replace(/[^\d]/g, '')
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'showPoster', config.showUrl)
        this.$set(this.param, 'poster', config.insertUrl)
        this.fileinfo = config
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    getActivityDetailInfo(activityId) {
      Promise.all(
        // 获取卡类型列表
        [
          cardList({}),
          activityQueryForEdit({
            param: {
              activityId
            }
          })
        ]
      )
        .then((res) => {
          const obj = res[1].record
          this.param = obj
          this.vipTypes = []
          const discountmap = res[1].record.discountMap
          if (res[1].record.cardTypes) {
            this.$set(this.param, 'cardTypeList', res[1].record.cardTypes.split(','))
          } else {
            this.$set(this.param, 'cardTypeList', [])
          }
          if (this.param.discountType === '1') {
            res[0].recordList.forEach((item) => {
              this.vipTypes.push({
                name: item.cardName,
                id: item.id,
                value: discountmap[item.id],
                disabled: discountmap[item.id]
              })
            })
            // console.log('-------', res[0].recordList)
          } else {
            res[0].recordList.forEach((item) => {
              if (item.status === '1') {
                this.vipTypes.push({
                  name: item.cardName,
                  id: item.id,
                  value: null
                })
              }
            })
            this.$set(this.param, 'discountMap', {})
          }
          console.log('-------', this.vipTypes)
          // if (res[1].record.discountType === '0') {
          //   this.$set(this.param, 'discountMap', {})
          // } else {
          //   this.$set(this.param, 'discountMap', discountmap)
          // }
        })
        .catch(() => { })
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    getCardList() {
      // 获取卡类型列表
      cardList({
        param: {
          type: ''
        }
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          res.recordList.forEach((item) => {
            this.vipTypes.push({
              name: item.cardName,
              id: item.id,
              value: null
            })
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      this.$set(this.param, 'poster', '')
      this.$set(this.param, 'showPoster', '')
    },
    getSpaceList(id) {
      this.$set(this.param, 'dd', [id, ''])
      spaceList({ param: { id }}).then((res) => {
        this.cdList = res.recordList
      })
    },
    onSubmit() {
      var currentDate = new Date().getTime()
      var startTime = new Date(this.param.startTime).getTime()
      var endTime = new Date(this.param.endTime).getTime()
      var applyEndTime = new Date(this.param.applyEndTime).getTime()
      if (endTime < startTime) {
        this.$message.warning(this.$t('message.hdjsbnzyks'))
        return
      }
      if (endTime <= currentDate) {
        this.$message.warning(this.$t('message.hdjsbnzydq'))
        return
      }
      if (applyEndTime > endTime) {
        this.$message.warning(this.$t('message.bmjzbnwyhdjs'))
        return
      }
      const param = { ...this.param }
      if (param.isXz && param.isXz === '1') {
        if (!param.signLimit) {
          return this.$message.warning(this.$t('message.qsr') + this.$t('message.bmrs'))
        }
      }
      param.cardTypes = param.cardTypeList.join(',')
      param.venueId = sessionStorage.getItem('venueId')
      if (this.activityId) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.subLoading = true
            activitySaveForEdit({ param: param })
              .then((res) => {
                // console.log(res)
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success(this.$t('message.editcg'))
                  this.$router.replace(`/activityManagement/activityManagementList?renovate=1`)
                }
              })
              .catch((er) => {
                this.subLoading = false
                console.log(er)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.subLoading = true
            startActivity({
              param: param
            })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success(this.$t('message.addcg'))
                  this.$router.replace(`/activityManagement/activityManagementList?renovate=1`)
                }
              })
              .catch((err) => {
                this.subLoading = false
                console.log(err)
              })
          } else {
            return false
          }
        })
      }
    },
    // 返回上一页
    goBack() {
      // this.$router.go(-1)
      this.$router.replace(`/activityManagement/activityManagementList`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 138px;
  height: 76.6px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}

.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 50px;
}
</style>
